/**
 * 141. 环形链表
 * https://leetcode-cn.com/problems/linked-list-cycle/
 */

const { createListNode } = require('../../libs/public');

// /**
//  * @param {ListNode} head
//  * @return {boolean}
//  */
// function hasCycle(head) {
//   if (!head) return false;
//   let node = head;
//   while (node) {
//     if (node.checked) return true;
//     node.checked = true;
//     node = node.next;
//   }
//   return false;
// }

/**
 * 快慢指针
 * @param {ListNode} head
 * @return {boolean}
 */
function hasCycle(head) {
  if (!head) return false;
  let node1 = head;
  let node2 = head.next;
  while (node2) {
    if (node1 === node2) return true;
    node1 = node1.next;
    node2 = node2.next;
    if (node2) node2 = node2.next;
  }
  return false;
}

let head;

head = createListNode([3, 2, 0, -4]);
head.next.next.next.next = head.next;
console.log(hasCycle(head) === true);

head = createListNode([1, 2]);
head.next.next = head;
console.log(hasCycle(head) === true);

head = createListNode([1]);
console.log(hasCycle(head) === false);
